package xyz.shu.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import xyz.shu.exception.ParamException;
import xyz.shu.exception.PermissioneException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 公共的异常处理
 * @author shujinhao
 */
@Slf4j
public class SpringExceptionResolver implements HandlerExceptionResolver {
    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object o, Exception e) {
        //获取url
        String url=request.getRequestURI().toString();
        ModelAndView mv=null;
        //默认异常消息
        String defaultMsg="System error";
        //.json .page
        //要求所有请求json数据的都使用.json结尾
        if (url.endsWith(".json")){
            if (e instanceof PermissioneException || e instanceof ParamException){
                JsonData result=JsonData.fail(e.getMessage());
                mv=new ModelAndView("jsonView",result.toMap());
            }else {
                log.error("unknow json exception,url:{}",url,e);
                JsonData result=JsonData.fail(defaultMsg);
                mv=new ModelAndView("jsonView",result.toMap());
            }
            //要求所有请求page页面的都使用.page结尾
        }else if (url.endsWith(".page")){
            log.error("unknow page exception,url:{}",url,e);
            JsonData result=JsonData.fail(defaultMsg);
            //自动寻找exception.jsp
            mv=new ModelAndView("exception",result.toMap());
        }else{
            //未知异常处理
            log.error("unknow exception,url:{}",url,e);
            JsonData result=JsonData.fail(defaultMsg);
            mv=new ModelAndView("jsonView",result.toMap());
        }
        return mv;
    }
}
